package core

import (
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/context"
	"reflect"
	"tyz/tools"

	//"github.com/kataras/iris/v12/core/router"
	"github.com/kataras/iris/v12/mvc"
	"iris_test/config"
	"iris_test/controllers"
	core_handle "iris_test/core/handles"
	"net/http"
	//"reflect"
)

func InitApp(maps map[string]interface{}) {
	initControllers()
	app := iris.New()
	app.Use(core_handle.DomainHandle)
	app.Use(core_handle.PrepareHandel)
	for k, v := range maps {
		mvc.Configure(app.Party(k), func(app *mvc.Application) {
			app.Handle(v)
		})
	}

	//根据访问地址，更改路由
	app.WrapRouter(func(w http.ResponseWriter, r *http.Request, router http.HandlerFunc) {
		ctx := app.ContextPool.Acquire(w, r)
		ctx.AddHandler(core_handle.DomainHandle, core_handle.PrepareHandel)
		context.Do(ctx, ctx.Handlers())
		if config.Conf["controller"] != nil && config.Conf["action"] != nil {
			_, ok := config.ControllerMap[config.Conf["controller"].(string)]
			if !ok {
				goto GOON
			}
			controller := config.ControllerMap[config.Conf["controller"].(string)]
			reflectVal := reflect.ValueOf(controller)
			methodName := tools.Ucfirst(config.Conf["action"].(string))
			method := reflectVal.MethodByName(methodName)
			if !method.IsValid() {
				goto GOON
			}
			res := method.Call(make([]reflect.Value, 0))
			if len(res) > 0 {
				tmp := res[0]
				switch tmp.Type().String() {
				case "string":
					ctx.Writef(tmp.String())
					break
				default:
					ctx.Writef("未知的返回类型")
					break
				}
				return
			}
  			ctx.Writef(fmt.Sprintf("执行%s%s没有返回值", config.Conf["controller"], method))
			return
		}
		GOON: router.ServeHTTP(w, r)
	});
	app.Run(iris.Addr(":9502"))
	config.App = app
}

func initControllers() {
	config.ControllerMap["news"] = new(controllers.NewsController)
	config.ControllerMap["products"] = new(controllers.ProductsController)
}
